#!/bin/bash

source './.config'

if [[ -z "$GAE_HOME" ]]; then
    echo "\$GAE_HOME not set."
    exit 1
fi

if [[ ! -d "gen" ]]; then
    mkdir 'gen'
fi

rm -rf gen/*

compile_templates() {
    local tmpl_home
    tmpl_home="${CLOSURE_HOME}/closure-templates-read-only"
    java -jar "${tmpl_home}/build/SoyToJsSrcCompiler.jar" \
	--shouldGenerateJsdoc \
	--outputPathFormat 'gen/js/{INPUT_FILE_NAME_NO_EXT}.js' \
        $(find src/soy -name '*.soy')
    # Copy the js files from the distribution.
    cp -u ${tmpl_home}/javascript/*.js gen/js
}

# Duplicate the directory hierarchy from 'src' to 'gen'
make_hierarchy() {
    local dirs
    dirs=$(find src/* -type d)
    for d in $dirs; do
	mkdir -p "gen/${d#src/}"
    done
}

# Copy files from 'src' to 'gen' according to matching pattern.
# $1 pattern
copy_files() {
    local files
    files=$(find src/* -type f -name "$1")
    for f in $files; do
	echo "copy $f -> gen/${f#src/}"
	cp -p "$f" "gen/${f#src/}"
    done
}

# Symink files from 'src' to 'gen' according to matching pattern.
# $1 pattern
symlink_files() {
    local files
    files=$(find src/* -type f -name "$1")
    for f in $files; do
	echo "symlink $f -> gen/${f#src/}"
	ln -s "$f" "gen/${f#src/}"
    done
}

##
# MAIN

make_hierarchy
compile_templates
copy_files '*.yaml'
copy_files '*.py'
copy_files '*.html'

